package com.example.zsq.myapplication;

import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import static com.example.zsq.myapplication.R.id.button;


public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {


    private ListView mListView;
    private List<Song>  list;
    private MyAdapter adapter;
    private MediaPlayer mediaPlayer;
    private  int PalyNum;
    public static  myhandler handler2;
    private static   SeekBar seekBar1;
    private TextView  textView1;
    private TextView  textView2;
    MucisService musicService;
    private RelativeLayout root_layout;
    static  int  ischang = 0;



    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        musicService = new MucisService();



        initView();
        Button bt1 = (Button)findViewById(button);
        bt1.setOnClickListener(send);
        Button bt2 = (Button)findViewById(R.id.button2);
        bt2.setOnClickListener(last);
        Button bt3 = (Button)findViewById(R.id.button6);
        bt3.setOnClickListener(next);
        seekBar1 = (SeekBar)findViewById(R.id.seekBar);
        root_layout = (RelativeLayout)findViewById(R.id.Relativelayout1);
        handler2 = new myhandler();
        textView1 = (TextView)findViewById(R.id.textView);
        textView2 = (TextView)findViewById(R.id.textView2);
        seekBar1.setOnSeekBarChangeListener(this);
        setTheme("背景1");
    }

/*
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        System.out.println("000000000000000000000");
    }

    // 开始拖动
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        System.out.println("111111111111111111111");
    }

    // 停止拖动
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        System.out.println("22222222222222222222");
    }*/

    public  void initView()
    {
        mediaPlayer = new MediaPlayer();
        mListView = (ListView)findViewById(R.id.main_listview);
        list = new ArrayList<>();
        list = MusicUtils.getMusicDate(this);
        adapter = new MyAdapter(this,list);
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //创建一个播放音频的方法，把点击到的地址传过去
                //list.get(i).path这个就是歌曲的地址
                play(list.get(i).path);
                findViewById(R.id.main_control_rl).setVisibility(View.VISIBLE);
                PalyNum = i ;
            }
        });


    }

    public  void play(String path)
    {

        Intent in = new Intent(this, MucisService.class)
                .putExtra("switch", path);
        //startActivity(in);
        startService(in);

        /*try{
        mediaPlayer.reset();
        mediaPlayer.setDataSource(path);
        mediaPlayer.prepareAsync();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){

        public void onPrepared(MediaPlayer mediaPlayer) {
            mediaPlayer.start();//开始音频
        }
    });
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }*/
    }

    public View.OnClickListener send = new View.OnClickListener() {
        public void onClick(View v)
        {
            Button b = (Button)v;
            String buttonText = b.getText().toString();
            System.out.println("this is "+buttonText);
            if(buttonText == "播放")
                b.setText("暂停");
            else
                b.setText("播放");
            Intent in = new Intent(MainActivity.this, MucisService.class)
                    .putExtra("stop", 1);
            startService(in);
        }
    };
    public View.OnClickListener last = new View.OnClickListener(){
        public void onClick(View v)
        {
            if(PalyNum<=0)
               System.out.println("this is the frist");
            else
                PalyNum--;
                play(list.get(PalyNum).path);
        }

    };
    public View.OnClickListener next = new View.OnClickListener(){
        public void onClick(View v)
        {
            if(PalyNum>=list.size() - 1) {
                PalyNum = 0;
                System.out.println("this is the last");
            }
            else
                PalyNum++;
                play(list.get(PalyNum).path);
        }

    };

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        System.out.println("1111111111111111111111");
        textView1.setText(getNOWTime(seekBar1.getProgress()));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {


        ischang = 1;
        System.out.println("000000000000000000000");
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        Intent in = new Intent(MainActivity.this, MucisService.class)
                .putExtra("stop", seekBar1.getProgress());
        startService(in);
        ischang = 0;

    }



      /* private  static    Handler handler = new Handler() {  //更新进度条和音乐播放时间
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.obj != null) {
                    String total = (String) msg.obj;

                }
                int progress = msg.what;
                int current = (int) (progress * MucisService.mp.getDuration() / 1000.0);
                seekBar1.setProgress(current);

            }
        };*/

      class  myhandler extends  Handler {
          public void handleMessage(Message msg) {
              //System.out.println( "this is the meg.what"+msg.what);
              //System.out.println("that is the meg.obj" + msg.obj);
             // System.out.println("that is the meg.1age" + msg.arg1);
             // System.out.println("that is the meg.2age" + msg.arg2);

             seekBar1.setMax(msg.arg1);

              System.out.println("that is the meg.2age" +getNOWTime(msg.arg2));
              if(ischang==0)
              textView1.setText(getNOWTime(msg.arg2));
              textView2.setText(getNOWTime(msg.arg1));
              if (msg.what == 6)
                  System.out.println("666666666666");

              else
                  System.out.println("-");
              if(ischang == 0) {
                  System.out.println("is chang is "+ischang);
                  seekBar1.setProgress(msg.arg2);
              }
              else
              {System.out.println("is chang6666 is "+ischang);}
          }
      }
    public String getNOWTime(int i) {                        //将毫秒转换成时间
        int total = i;
        String format = "mm:ss";                     //自定义时间模式
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(total);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu){

        getMenuInflater().inflate(R.menu.main,menu);
        //如果返回false，创建的菜单无法显示
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item){
        //通过调用item.getItemId()来判断菜单项
        switch (item.getItemId()){
            case R.id.menu_theme:
                new AlertDialog.Builder(this).setTitle("请选择主题").setItems(R.array.theme,
                        new DialogInterface.OnClickListener()
                        {
                            @Override
                            public  void onClick(DialogInterface dialog,int which)
                            {
                                String[] themes =MainActivity.this.getResources().getStringArray(R.array.theme);
                                setTheme(themes[which]);
                            }
                        }).show();


                //Toast.makeText(this,"You Clicked Add",Toast.LENGTH_SHORT).show();
                break;
            case R.id.menu_about:
                Toast.makeText(this,"本APP制作于2017年9月25号",Toast.LENGTH_SHORT).show();
                break;
            case R.id.menu_quit:
                new AlertDialog.Builder(this).setTitle("提示").setMessage("你确定要退出？").setPositiveButton("对！",
                        new DialogInterface.OnClickListener()
                        {
                            @Override
                            public  void onClick(DialogInterface dialog,int agr1)
                            {
                                System.exit(0);
                            }
                        }).setNegativeButton("算了", new DialogInterface.OnClickListener()
                {
                    @Override
                    public  void onClick(DialogInterface dialog,int agr1)
                    {

                    }

            }).show();
            default:
        }
        return true;
    }
    public void setTheme(String theme)
    {
       /* if("背景1".equals(theme))
        {
            root_layout.setBackgroundResource(R.drawable.p1);
        }
        else
            root_layout.setBackgroundResource(R.drawable.p2);*/
       switch(theme)
       {
           case "背景1":
               root_layout.setBackgroundResource(R.drawable.p1);
               break;
           case "背景2":
               root_layout.setBackgroundResource(R.drawable.p2);
               break;
           case "背景3":
               root_layout.setBackgroundResource(R.drawable.p3);
               break;
           case "背景4":
               root_layout.setBackgroundResource(R.drawable.p4);
               break;
           case "背景5":
               root_layout.setBackgroundResource(R.drawable.p5 );
               break;
       }
    }
}
